//
//  AppDelegate.m
//  BaiYing_Thinker
//
//  Created by 鹏 朱 on 15/10/13.
//  Copyright (c) 2015年 XKJH. All rights reserved.
//

#import "AppDelegate.h"
#import "RemoteNotificationManage.h"
#import "DatabaseCache.h"
#import "FileMangeHelper.h"
#import "SessonContentMessage.h"
#import "NSDate+Addition.h"
#import "UploadFile.h"
#import "XKJHNavRootController.h"
#import "XKJHBaseNavigationBar.h"
#import "MainChatController.h"
#import "iflyMSC/IFlyMSC.h"
#import <AlipaySDK/AlipaySDK.h>
#import "WXApi.h"
#import "NSString+MD5.h"

static NSTimeInterval const kTimeNotSound = 5;  //在此时间内收到消息不发出提示音

@interface AppDelegate ()<WXApiDelegate>

@property (nonatomic, strong) NSString *sysCode;
@property (nonatomic, assign) NSTimeInterval lastSoundTime;

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    //初始化
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];

    [self initInfo];
    [self InitIFlySetting];

    if (SIMULATOR == 1) {
        [self initIMServerInfo];
    }

    MainChatController *rootVC = [[MainChatController alloc] init];
    self.window.rootViewController = rootVC;
    self.rootVC = rootVC;
    
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    
    [self disConnect];
    
}

- (void)applicationWillEnterForeground:(UIApplication *)application {

}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    
    [self connectToServer];
    
}

- (void)applicationWillTerminate:(UIApplication *)application {

}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation{
    
    if ([url.host isEqualToString:@"safepay"]) {
        
        //支付宝页面传递url
        [[AlipaySDK defaultService] processOderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            
        }];
        
        return YES;
    } else if ([url.host isEqualToString:@"pay"]) {
        
        
        return [WXApi handleOpenURL:url delegate:self];
        
    } else {
        
        //语音合成传递url
        [[IFlySpeechUtility getUtility] handleOpenURL:url];

    }
    
    return YES;
}

/**
 *  IOS7隐藏状态栏
 *
 *  @return 状态栏属性
 */
- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}

/**
 *  IOS7隐藏状态栏
 *
 *  @return 是否隐藏状态栏
 */
- (BOOL)prefersStatusBarHidden
{
    return YES;
}

- (void)initInfo {
    
    self.openSound = YES;
    self.lastSoundTime = 0;
    
    //隐藏状态栏
    [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationNone];

    //注册远程通知
    [[RemoteNotificationManage sharedRemoteNotificationManage] registerNotification];
    
    //创建本地数据库
    [[FileMangeHelper shareInstance] createDatabaseFolder];
    [[DatabaseCache shareInstance] createDBWithPath:[[DatabaseCache shareInstance] getDbPath]];
    
}

- (void)initIMServerInfo {
    
    if (SIMULATOR == 1) {
        _currentUser = [NSString stringWithFormat:@"I_%@",[Util macaddress]];
    } else {
        _currentUser = [NSString stringWithFormat:@"I_%@", [self.deviceToken MD5]];
    }
    
    _topic = [NSString stringWithFormat:@"%@%@",_currentUser, @"_topic"];
    
    [self initReachability];
}

- (void)InitIFlySetting {
    
    //设置sdk的log等级，log保存在下面设置的工作路径中
    [IFlySetting setLogFile:LVL_ALL];
    
    //打开输出在console的log开关
    [IFlySetting showLogcat:YES];
    
    //设置sdk的工作路径
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cachePath = [paths objectAtIndex:0];
    [IFlySetting setLogFilePath:cachePath];
    
    //创建语音配置,appid必须要传入，仅执行一次则可
    NSString *initString = [[NSString alloc] initWithFormat:@"appid=%@",APPID_VALUE];
    
    //所有服务启动前，需要确保执行createUtility
    [IFlySpeechUtility createUtility:initString];

}

- (void)initReachability {
    
    _reach = [Reachability reachabilityWithHostname:@"www.baidu.com"];
    _reach.reachableOnWWAN = NO;

    WEAK_SELF
    _reach.reachableBlock = ^(Reachability*reach) {
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"REACHABLE!");
            [weak_self connectToServer];

        });
    };
    
    _reach.unreachableBlock = ^(Reachability*reach) {
        NSLog(@"UNREACHABLE!");
        [weak_self disConnect];
        [weak_self performSelector:@selector(connectToServer) withObject:weak_self afterDelay:2];
    };
    
    [_reach startNotifier];
    
}

- (NSString *)messageId {
    
    NSString *message_id = [NSString stringWithFormat:@"%@:%@",self.currentUser,[Util createTimeIntervalWithDate:[NSDate date]]];
    return message_id;

}

- (void)connectToServer
{
    if (_currentUser && !_hasConnectToIMserver) {
        self.session = [[MQTTSession alloc] initWithClientId:self.currentUser];
        self.session.delegate = self;
        [self.session connectToHost:kIP port:KPort];
    }
}

- (void)reconnection {
    
    if (_currentUser && !_hasConnectToIMserver) {
        if (!self.session) {
            self.session = [[MQTTSession alloc] initWithClientId:self.currentUser];
            self.session.delegate = self;
        }
        
        [self.session connectToHost:kIP port:KPort];
    }

}

- (void)disConnect
{
    [self.session close];
    self.session.delegate = nil;
    self.session = nil;
    _hasConnectToIMserver = NO;
}

- (void)sendLocationMessage {
    
    NSDictionary *msgDict = @{@"clientid":_currentUser,@"latitude":@"22.554495",@"longitude":@"113.949166"};
    
    
    [[UploadFile shareInstance] sendMessageWithDictionary:msgDict url:[NSString stringWithFormat:@"http://%@:%d/api/geo",kUploadIP,KUploadPort]];
}

- (void)sendAddressBookMessage {
    
    NSDictionary *msgDict = @{@"clientid":_currentUser,@"includes":@[@"18098768393",@"18098768333",@"18098762393",@"18091238393",@"18045646593",@"18091238855",@"18098798643",@"18093453455"]};
    
    [[UploadFile shareInstance] sendMessageWithDictionary:msgDict url:[NSString stringWithFormat:@"http://%@:%d/api/phoneaddress",kUploadIP,KUploadPort]];
    
}

- (void)subscribe:(NSString *)topic {
    
    [self.session subscribeTopic:topic];
    
    //上传位置信息
    [self sendLocationMessage];
    
    //上传通讯录
    [self sendAddressBookMessage];
    
}

- (void)sendMessage:(NSDictionary *)msg {
    
    [self.session publishJson:msg onTopic:kTopic];
}

/**
 *  把收到的消息存入本地数据库
 *
 *  @param dic 收到的消息字典
 */
- (void)localCacheWithDictionary:(NSDictionary *)dic {
    
    SessonContentMessage *message = [[SessonContentMessage alloc] initWithDictionary:dic isMyself:@0];
    
    [[DatabaseCache shareInstance] addSessionContentInfo:message];
    
    NSDictionary *parameterDic = [[NSDictionary alloc] initWithObjectsAndKeys:message,KMessageParameter, nil];
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center postNotificationName:kNotificationReceiveNewMessage object:nil userInfo:parameterDic];
}

- (void)handleResponseString:(NSString *)jsonString {
    
    if (!IsEmpty(jsonString)) {
       
        NSDictionary *payloadDic = [NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableLeaves error:nil];
        
  //插件测试数据
//        payloadDic = @{@"clientid":@"S_251",@"content":@{@"component":@{@"id":@"20292",@"name":@"order",@"rule":@"input\":{\"processkey\":\"PlanOrder20\",\"orderid\":\"9250.653382477747\",\"serviceid\":\"9250.653382477747\"},\"output\":\"payway,username,price,serviceid,processkey\"",@"url":@"http://192.168.1.153:8080/c/order.zip",@"version":@"1.0.0"},@"timestamp":@1446695705757,@"type":@"COMPONENT"},@"model":@"TALK",@"msg_id":@"I_E0:AC:CB:80:C6:EE:1446695653",@"to_range":@{@"lbskm":@1,@"rel":@"FRIENDS"},@"toclientid":@"I_E0:AC:CB:80:C6:EE"};
        
        NSString *payloadType = payloadDic[@"model"];
        NSString *messageId = payloadDic[@"msg_id"];
        NSString *sys_code = payloadDic[@"content"][@"sys_code"];
        NSString *content_type = payloadDic[@"content"][@"type"];
        
        if (![sys_code isEqualToString:@"1006"] && ![sys_code isEqualToString:@"1005"]) {
            
            
            if (self.openSound) {
                NSTimeInterval time = [[NSDate date] timeIntervalSince1970];
                if (time - _lastSoundTime > kTimeNotSound) {
                    AudioServicesPlaySystemSound(1312);
                    _lastSoundTime = time;
                }
            }
            [self localCacheWithDictionary:payloadDic];
        }
        if ([content_type isEqualToString:@"COMPONENT"]) {
            
            NSString *filePath = [[FileMangeHelper shareInstance] getDownloadPathFromFileType:UploadFileZipType];
            NSString *documentName = [NSString stringWithFormat:@"%@_%@",payloadDic[@"content"][@"component"][@"id"],payloadDic[@"content"][@"component"][@"version"]];
            
            [[FileMangeHelper shareInstance] downloadFileURL:payloadDic[@"content"][@"component"][@"url"] savePath:filePath documentName:documentName completion:^(NSString *htmlUrl) {
                
                NSLog(@"html:%@",htmlUrl);
                
            }];
        }
        
        if ([payloadType isEqualToString:@"SYSTEM"]) {
            
            if ([sys_code isEqualToString:@"1000"]) {
                
            } else if ([sys_code isEqualToString:@"1001"]) {
                
            } else if ([sys_code isEqualToString:@"1004"]) {
                
                NSLog(@"成功了！");
                
            } else if ([sys_code isEqualToString:@"1005"]) {
                NSLog(@"开始百应之旅");
                
            } else if ([sys_code isEqualToString:@"1006"]) {
                
                if (self.deviceToken) {
                    NSDictionary *msgDict = @{@"clientid":_currentUser,@"content":@{@"sys_code":sys_code,@"text":self.deviceToken,@"type":@"TEXT"},@"model":@"SYSTEM",@"msg_id":messageId,@"apn_token":self.deviceToken};
                    [self sendMessage:msgDict];
                }
            }
        } else {
            
        }
    }
}

#pragma mark - MQtt Callback methods

- (void)session:(MQTTSession*)sender handleEvent:(MQTTSessionEvent)eventCode {
    switch (eventCode) {
        case MQTTSessionEventConnected:
        
        NSLog(@"connected");
        [self subscribe:_topic];
        _hasConnectToIMserver = YES;

        break;
        case MQTTSessionEventConnectionRefused:
        
        NSLog(@"connection refused");
        _hasConnectToIMserver = NO;
            
        break;
        case MQTTSessionEventConnectionClosed:
        
        NSLog(@"connection closed");
        _hasConnectToIMserver = NO;
        
        break;
        case MQTTSessionEventConnectionError:
        
        NSLog(@"connection error,reconnecting...");
        _hasConnectToIMserver = NO;
            
        break;
        case MQTTSessionEventProtocolError:
        
        NSLog(@"protocol error");
        _hasConnectToIMserver = NO;
            
        break;
        default:
        
        break;
    }
}

- (void)session:(MQTTSession*)sender
     newMessage:(NSData*)data
        onTopic:(NSString*)topic {

    NSString *payloadString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    [self handleResponseString:payloadString];
    NSLog(@"data: %@ %@", payloadString, data);
    
}

#ifdef __IPHONE_8_0
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
{
    //register to receive notifications
//    [application registerForRemoteNotifications];    
}
#endif

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    // 新获取的deviceToken
    NSString* newToken = [deviceToken description];
    newToken = [newToken stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
    newToken = [newToken stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    [[RemoteNotificationManage sharedRemoteNotificationManage] registerForRemoteNotificationsWithDeviceToken:newToken];
    self.deviceToken = newToken;
    
    [self initIMServerInfo];
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    
    [application cancelAllLocalNotifications];
    [application setApplicationIconBadgeNumber:0];

    [[RemoteNotificationManage sharedRemoteNotificationManage] failToRegisterForRemoteNotificationsWithError:error];
    
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    
    [[RemoteNotificationManage sharedRemoteNotificationManage] receiveRemoteNotification:userInfo];
    
    NSLog(@"aps:%@",userInfo[@"aps"]);
    [application setApplicationIconBadgeNumber:[userInfo[@"aps"][@"badge"] integerValue]];
    
    //播放声音
    if (self.openSound) {
        NSTimeInterval time = [[NSDate date] timeIntervalSince1970];
        if (time - _lastSoundTime > kTimeNotSound) {
            AudioServicesPlaySystemSound(1312);
            _lastSoundTime = time;
        }
    }

    [self localCacheWithDictionary:userInfo];
    
}

#pragma mark- WXApiDelegate

- (void)onResp:(BaseResp*)resp
{
    if ([resp isKindOfClass:[PayResp class]]) {
        PayResp *response = (PayResp *)resp;
        switch (response.errCode) {
                
            case WXSuccess:
                
                break;
                
            default:
                
                break;
        }
    }
}

@end
